package tools

import java.nio.file.Files

import config.{Global, MyFile}
import org.apache.commons.io.FileUtils
import play.api.data.Form
import play.api.data.FormBinding.Implicits._
import play.api.data.Forms._
import play.api.libs.json.{JsObject, Json}
import play.api.mvc.{AnyContent, Request}
import utils.ExecCommand


object GeneWise extends MyFile {

  case class GeneWiseData(proteinSeq: String, dnaSeq: String, para: String, pretty: String, genes: String, trans: String,
                          cdna: String, embl: String, ace: String, gff: String, diana: String, init: String,
                          splice: String, random: String, alg: String)

  val GeneWiseForm: Form[GeneWiseData] = Form(
    mapping(
      "proteinSeq" -> text,
      "dnaSeq" -> text,
      "para" -> text,
      "pretty" -> text,
      "genes" -> text,
      "trans" -> text,
      "cdna" -> text,
      "embl" -> text,
      "ace" -> text,
      "gff" -> text,
      "diana" -> text,
      "init" -> text,
      "splice" -> text,
      "random" -> text,
      "alg" -> text
    )(GeneWiseData.apply)(GeneWiseData.unapply)
  )

  def genewise(implicit request: Request[AnyContent]): JsObject = {
    var valid = "true"
    var msg = ""
    var out = ""
    try {

      val data = GeneWiseForm.bindFromRequest.get
      val tmpDir = Files.createTempDirectory("tmpDir").toString
      val proteinFile = tmpDir + "/pro.fa"
      FileUtils.writeStringToFile(proteinFile.toFile, data.proteinSeq)
      val dnaFile = tmpDir + "/dna.fa"
      FileUtils.writeStringToFile(dnaFile.toFile, data.dnaSeq)

      val outFile = s"$tmpDir/result.txt".toFile

      val execCommand = new ExecCommand
      val command = "genewise " + proteinFile + " " + dnaFile + " -kbyte 4000 " + " -init " + data.init + " -null  " +
        data.random + " -alg " + data.alg + data.para + data.pretty + data.genes + data.trans + data.cdna + data.embl +
        data.ace + data.gff + data.diana + data.splice
      execCommand.execot(command, outFile, tmpDir)
      if (execCommand.isSuccess) {
        out = outFile.readFileToString
      } else {
        valid = "false";
        msg = execCommand.getErrStr
      }
      tmpDir.delete
    } catch {
      case e: Exception => valid = "false"; msg = e.getMessage
    }

    if (Global.isWindow) {
      valid = "true";
      out = s"${Global.testResult}/genewise/result.txt".readFileToString
    }
    Json.obj("valid" -> valid, "msg" -> msg, "out" -> out)

  }


}
